﻿function formLoad(formid, recordid, otherGridInitCall, callback) {
    $.getJSON("/Tools/JSON.ashx?param=form&act=showinfo&formid=" + formid + "&recordid=" + recordid, function (json) {
        for (var i in json) {
            // if (typeof (json[i]) != "object") {
            var obj = $("[name=" + i.toUpperCase() + "]");
            if (obj.size() < 1)
                obj = $("[name=" + i + "]");
            if (obj.size() < 1)
                obj = $("#" + i);
            var nodeName = null;
            var v = json[i];
            if (obj.size() > 0)
                nodeName = obj[0].nodeName.toLowerCase();
            if (!v || v == null)
                v = "";
            switch (nodeName) {
                case "input":
                    var type = obj.attr("type").toLowerCase();
                    switch (type) {
                        case "text":
                            obj.val(v);
                            break;
                        case "radio":
                            obj.filter("[value=" + v + "]").attr("checked", "true");
                            break;
                        case "checkbox":
                            if (v == true || (typeof (v) == "string" && v.toLowerCase() == "true")) {
                                obj.attr("checked", "true");
                            }
                            else
                                obj.removeAttr("checked");
                        default:
                            obj.val(v);
                            break;
                    } //end switch type
                    break;
                case "select":
                    if (v && v != "") {
                        if (obj.find("option[value=" + v + "]").size() > 0) {
                            obj.attr("value", v);
                        }
                        else {
                            obj.append("<option value=" + v + ">" + v + "</option>");
                        }
                    }
                    break;
                case "textarea":
                    //obj.text(v);
                    obj.val(v);
                    break;
                case "table":
                    if (obj.size() > 0) {
                        for (var j in json[i]) {
                            if (typeof (json[i][j]) == "function")
                                continue;
                            obj.addRowData(json[i][j]["Id"], json[i][j]);
                        }
                    }
                    break;
                default:
                    break;
            }
            if (typeof (otherGridInitCall) == "function") {
                otherGridInitCall(json[i]);
            }
            // }
        } //end for
        if (callback && typeof (callback) == "function") {
            callback(json);
        }
    });
}
function formSubmit(formid, exdata, callback) {
    if (!exdata)
        exdata = [];
    $("table[id]").each(function () {
        var id = $(this).attr("id");
        if (id && id != "") {
            var lastId = getjqGridLastSel(id);
            if (lastId) {
                jQuery('#' + id).jqGrid('saveRow', lastId, false, "clientArray");
            }
            var listjson = jQuery("#" + id).getRowData();
            var keyField = getjqGridKeyField(id);
            var keyColProp = jQuery("#" + id).getColProp(keyField);
            if (keyColProp && keyColProp["sorttype"] == "int") {
                for (var i in listjson) {
                    if (typeof (listjson[i]) == "function")
                        continue;
                    if (listjson[i][keyField] && !isNaN(listjson[i][keyField]) && listjson[i][keyField] < 0) {
                        listjson[i][keyField] = 0;
                    }
                }
            }
            exdata.push({ name: id, value: JSON.stringify(listjson) });

        }
    });
    var json = $("form").serializeArray();
    if (typeof (exdata) != "undefined" && exdata) {
        for (var i in exdata) {
            json.push(exdata[i]);
        }
    }
    $.ajax({
        url: "/Tools/Submit.ashx?formid=" + formid,
        data: json,
        type: "POST",
        success: function (data) {
            if (typeof (callback) != "undefined") {
                callback(data);
            } else
                alert("保存成功!");
        }
    });
}
function FormDelete(formid, recordid, callback) {
    $.ajax({
        url: "/Tools/Submit.ashx?formid=" + formid,
        data: {
            formid: formid,
            recordid: recordid,
            action: "delete"
        },
        type: "POST",
        success: function (data) {
            if (typeof (callback) != "undefined") {
                callback(data);
            }
        }
    });
}

//表格加载.
function gridLoad(gridid, setting, AssignObject) {
    var setting2 = {
        datatype: 'local',
        rownumbers: true,
        cellsubmit: 'clientArray',
        shrinkToFit: false,
        loadonce: true,
        pager: '#gridpager' + gridid,
        onSelectRow: function (id) {
            SelectGridRow(gridid, id);
        }
    };
    $.extend(setting2, setting);
    jQuery("#" + gridid).jqGrid(setting2);
    jQuery("#" + gridid).navGrid('#gridpager' + gridid, { edit: false, add: false, del: false, search: false })
    .navButtonAdd('#gridpager' + gridid, { caption: "增加", buttonicon: "ui-icon-plus", position: "last",
        onClickButton: function () {
            AddGridRow(gridid, AssignObject);
        }
    }).navButtonAdd('#gridpager' + gridid, { caption: "删除", buttonicon: "ui-icon-cancel", position: "last",
        onClickButton: function () {
            DeleteCurGridRow(gridid);
        }
    });
}

//添加一行记录.
function AddGridRow(gridid, AssignObject) {
    var jGrid = jQuery("#" + gridid);
    var keyDataType = "string";
    var keyField = getjqGridKeyField(gridid);
    var keyCol = jGrid.getColProp(keyField);
    if (keyCol && keyCol["sorttype"])
        keyDataType = keyCol["sorttype"];
    var lastSel = getjqGridLastSel(gridid);
    if (lastSel) { jGrid.jqGrid('saveRow', lastSel, false, "clientArray"); }
    var row = {};
    //如果子表的主键是GUID 那么就生成一个GUID
    //如果子表的主键是INT类型,那么数据库里就一定要设置为自动增长
    if (keyDataType == "string")
        row[keyField] = newGuid();
    else {
        var cols = jGrid.getCol(keyField);
        if (!cols || cols.length < 1)
            row[keyField] = 0;
        else {
            var minKey = Math.min.apply(this, cols);
            if (minKey > 0)
                row[keyField] = 0;
            else {
                row[keyField] = minKey - 1;
            }
        }
    }
    //数据整合到一起.
    $.extend(row, AssignObject);
    jGrid.addRowData(row["Id"], row);
    jGrid.editRow(row["Id"], true);
    lastSel = row["Id"];
    setjqGridLastSel(gridid, lastSel);
}
//删除一条记录.
function DeleteCurGridRow(gridid) {
    var id = jQuery("#" + gridid).getGridParam("selrow");
    //先保存当前行
    var lastSel = getjqGridLastSel(gridid);
    if (lastSel) {
        jQuery("#" + gridid).jqGrid('saveRow', lastSel, false, "clientArray");
    }
    if (id) jQuery("#" + gridid).jqGrid("delRowData", id);
}

function getjqGridLastSel(gridid) {
    var lastsel = null;
    var grid = $("#" + gridid);
    if (grid.size() > 0)
        lastsel = grid.attr("lastsel");
    if (lastsel == "")
        lastsel = null;
    return lastsel;
}
//获取表格的主键名称
function getjqGridKeyField(gridid) {
    var options = $("#" + gridid).jqGrid("getGridParam", "colModel");
    var keyField = "Id";
    $(options).each(function (e, f) {
        if (this["key"] && this["key"] === true) {
            keyField = this["name"];
            return;
        }
    });
    return keyField;
}
function setjqGridLastSel(gridid, lastSel) {
    var grid = $("#" + gridid);
    if (grid.size() > 0)
        grid.attr("lastsel", lastSel);
}

function SelectGridRow(gridid, id) {
    var lastSel = getjqGridLastSel(gridid);
    if (id && lastSel && id !== lastSel) {
        jQuery('#' + gridid).jqGrid('saveRow', lastSel, false, "clientArray");
        setjqGridLastSel(gridid, "");
    }
    jQuery('#' + gridid).editRow(id, true);
    setjqGridLastSel(gridid, id);
}